﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Collection.Entities;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Net;

using System.Collections.Specialized;
using WanPiJie.Products;
namespace Collection.Core.Processing
{
	/// <summary>
	/// 属性串解析类
	/// </summary>
	public class Parser
	{
		/// <summary>
		/// 解析指定类目的指定属性串
		/// </summary>
		/// <param name="catalogId">指定的类目Id</param>
		/// <param name="valueString">属性串</param>
		/// <returns>返回解析结果</returns>
		public static List<ComplexProperty> Parse(long catalogId, string valueString)
		{
			string[] values;
			var category = ServiceFactory.CatalogService.GetCatalogById(catalogId);
			List<ComplexProperty> analyticalResults = new List<ComplexProperty>();
			Dictionary<long, string> propertyDictionary = DecomposeProperties(valueString);
			foreach (long key in propertyDictionary.Keys)
			{
				if (propertyDictionary[key].Contains('&'))
				{
					values = propertyDictionary[key].Split('&');
					foreach (string value in values)
					{
						analyticalResults.Add(new ComplexProperty(key.ToString(), value, category
							, ServiceFactory.CatalogService.GetPropertyValue(catalogId, key, int.Parse(value))));
					}
				}
				else
				{
					analyticalResults.Add(new ComplexProperty(key.ToString(), propertyDictionary[key], category
							, ServiceFactory.CatalogService.GetPropertyValue(catalogId, key, int.Parse(propertyDictionary[key]))));
				}
			}
			return analyticalResults;
		}

		/// <summary>
		/// 分解属性串（20000:3217426;7253738:71036670;20029:28316;6797511:50288;）
		/// </summary>
		/// <returns>返回字典形式的值</returns>
		public static Dictionary<long, string> DecomposeProperties(string propString)
		{
			string[] pair;
			Dictionary<long, string> propertyDictionary = new Dictionary<long, string>();
			var propertyPairs = propString.Split(';');
			foreach (var propertyPair in propertyPairs)
			{
				pair = propertyPair.Split(':');
				if (propertyDictionary.ContainsKey(long.Parse(pair[0])))
				{
					propertyDictionary[long.Parse(pair[0])] = string.Concat(propertyDictionary[long.Parse(pair[0])], "&", pair[pair.Length - 1]);
				}
				else
				{
					propertyDictionary.Add(long.Parse(pair[0]), pair[pair.Length - 1]);
				}
			}
			return propertyDictionary;
		}
	}
}